from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from libs.yuntongxun.sms import CCP
from .serializers import RegisterSmsCodeSerializer
from . import contants
from libs.captcha.captcha import captcha


class RegisterImageCodeAPIView(APIView):

    def get(self,request,image_code_id):

        text,image = captcha.generate_captcha()

        redis_conn = get_redis_connection("code")
        redis_conn.setex('img_%s' %image_code_id,contants.IMAGE_CODE_REDIS_EXPIRES,text)

        return HttpResponse(image,content_type="image/jpeg")


# class RegisterSmsCodeAPIView(APIView):
#     def get(self,request,mobile):
#
#         query_params = request.query_params
#
#         # text = query_params.get("text")
#         # image_code = query_params.get("image_code")
#         serializer = RegisterSmsCodeSerializer(data=query_params)
#         serializer.is_valid(raise_exception=True)
#
#         from random import randint
#         sms_code = '%06d' %randint(0,999999)
#
#         # CCP().send_template_sms(mobile,[sms_code,5],1)
#         from celery_tasks.sms.tasks import send_sms_code
#         send_sms_code.delay(mobile,sms_code)
#
#         redis_conn = get_redis_connection("code")
#         redis_conn.setex('sms_%s'%mobile,300,sms_code)
#
#         return Response({"msg":"ok"})


#使用二级视图
from .serializers import RegisterSmsCodeSerializer
from rest_framework.generics import GenericAPIView


class RegisterSmsCodeAPIView(GenericAPIView):

    serializer_class = RegisterSmsCodeSerializer

    def get(self, request, mobile):

        query_params = request.query_params
        serializer = self.get_serializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        from random import randint
        sms_code = '%06d' %randint(0,999999)

        #CCP().send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        redis_conn = get_redis_connection("code")
        redis_conn.setex('sms_%s'%mobile,300,sms_code)

        return Response({"msg":"ok"})

